package com.rory.controller.interceptor;

import com.rory.entity.generate.User;
import com.rory.util.IpMacUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器 create by Rory
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Login login = method.getMethodAnnotation(Login.class);
            if (login != null) {
                User user = (User) request.getSession().getAttribute("user");
                if (user == null) {
                    IpMacUtil.getLoggerOutput("用户没有登录");
                    response.sendRedirect(request.getContextPath() + "/");
                    return false;
                }
            }
        }
        return true;
    }
}
